/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * EnterCubes.java
 *
 * Created on 11/05/2011, 20:38:08
 */
package Monopol.Cubes;

import Utils.Utils;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;

/**
 *
 * @author Assaf
 */
public class EnterCubes extends javax.swing.JFrame {
    private Integer cube1, cube2;
    private boolean finished = false;
    private Integer timer;

    /** Creates new form EnterCubes */
    public EnterCubes(Integer seconds) {
	initComponents();
	// Verify that the Cubes Text Label are Null
	lblCube1.setText("");
	lblCube2.setText("");
	cube1 = 0;
	cube2 = 0;
	// Set the Time in Seconds
	timer = seconds * 1000;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        txtCube1 = new javax.swing.JTextField();
        txtCube2 = new javax.swing.JTextField();
        lblCube1 = new javax.swing.JLabel();
        lblCube2 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        txtCube1.addInputMethodListener(new java.awt.event.InputMethodListener() {
            public void caretPositionChanged(java.awt.event.InputMethodEvent evt) {
            }
            public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) {
                txtCube1InputMethodTextChanged(evt);
            }
        });

        txtCube2.addInputMethodListener(new java.awt.event.InputMethodListener() {
            public void caretPositionChanged(java.awt.event.InputMethodEvent evt) {
            }
            public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) {
                txtCube2InputMethodTextChanged(evt);
            }
        });

        lblCube1.setText("jLabel1");

        lblCube2.setText("jLabel2");

        jButton1.setText("Set the Dices");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel1.setText("Second Cube:");

        jLabel2.setText("First Cube:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(16, 16, 16)
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtCube1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(54, 54, 54)
                                .addComponent(lblCube1)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel1)
                            .addComponent(lblCube2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtCube2, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(15, 15, 15))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(110, 110, 110)
                        .addComponent(jButton1)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblCube1)
                    .addComponent(lblCube2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 75, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtCube1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(txtCube2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(59, 59, 59)
                .addComponent(jButton1)
                .addGap(29, 29, 29))
        );

        txtCube1.getDocument().addDocumentListener(new DocumentListener() {
            public void changedUpdate(DocumentEvent e) { textChanged(e); }
            public void insertUpdate(DocumentEvent e) { textChanged(e); }
            public void removeUpdate(DocumentEvent e) { textChanged(e); }
            private void textChanged(DocumentEvent e)
            {
                Integer value = cubeTextChanged(e, lblCube1);
                cube1 = value;
            }
        });
        txtCube2.getDocument().addDocumentListener(new DocumentListener() {
            public void changedUpdate(DocumentEvent e) { textChanged(e); }
            public void insertUpdate(DocumentEvent e) { textChanged(e); }
            public void removeUpdate(DocumentEvent e) { textChanged(e); }
            private void textChanged(DocumentEvent e)
            {
                Integer value = cubeTextChanged(e, lblCube2);
                cube2 = value;
            }
        });

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtCube2InputMethodTextChanged(java.awt.event.InputMethodEvent evt) {//GEN-FIRST:event_txtCube2InputMethodTextChanged
    }//GEN-LAST:event_txtCube2InputMethodTextChanged

    private void txtCube1InputMethodTextChanged(java.awt.event.InputMethodEvent evt) {//GEN-FIRST:event_txtCube1InputMethodTextChanged
    }//GEN-LAST:event_txtCube1InputMethodTextChanged

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
	close();
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * Detects when the text was changed and Displays the Cube Image to Comply with the Number
     * @param evt The Text Change Document Event
     * @param cubeLabel the Cube Label to change
     * @return The Cube Integer Value
     */
    private Integer cubeTextChanged(DocumentEvent evt, JLabel cubeLabel) {
	Document doc = (Document) evt.getDocument();
	String strNum = "0";
	Integer val = 0;
	try {
	    strNum = doc.getText(0, doc.getLength());
	} catch (BadLocationException ex) {
	    Logger.getLogger(EnterCubes.class.getName()).log(Level.SEVERE, null, ex);
	}
	try {
	    // Check the Input Number
	    val = checkNumbers(Integer.parseInt(strNum));
	    // Set the Cube Picture
	    cubeLabel.setIcon(getCubePicture(val));
	} catch (NumberFormatException e) {
	    if (!strNum.isEmpty()) {
		Utils.writeText("You can Enter only Numbers between 1 and 6");
	    }
	}
	return val;
    }

    /**
     * Checks that the Input number is a valid cube number (between 1 to 6)
     * @param inNumber The Input Number
     * @return A Valid Cube number
     */
    private Integer checkNumbers(Integer inNumber) {
	Integer outNumber = 0;
	if (inNumber > 0 && inNumber < 7) {
	    outNumber = inNumber;
	} else {
	    if (inNumber >= 7) {
		outNumber = 6;
	    } else if (inNumber <= 0) {
		outNumber = 1;
	    }
	}
	// Return the Number
	return outNumber;
    }

    /**
     * Returns the Cube Icon accourding to the Input Number
     * @param num The Input Cube Number
     * @return The Cube Image Icon
     */
    private ImageIcon getCubePicture(Integer num) {
	return Utils.getImageIcon("/cubes/" + num + "cube.png");
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
	java.awt.EventQueue.invokeLater(new Runnable() {

	    public void run() {
		new EnterCubes(15).showDialog();
	    }
	});
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel lblCube1;
    private javax.swing.JLabel lblCube2;
    private javax.swing.JTextField txtCube1;
    private javax.swing.JTextField txtCube2;
    // End of variables declaration//GEN-END:variables

    /**
     * Closes the Frame 
     */
    private void close() {
	finished = true;
    }

    /**
     * Shows the Dialog and returns the Cubes Array
     * @return The Cubes Array
     */
    public Integer[] showDialog(){
	this.setVisible(true);
	this.setBounds(Utils.posCenterScreen(getWidth()   ,getHeight()));
	Integer[] arrCubes = new Integer[2];
	// Create a Closing Timer
	Timer closeTimer = new Timer("Manual Cubes Close Timer", true);
	// Set the Timer a Task
	closeTimer.schedule(new TimerTask() {

	    @Override
	    public void run() {
		close();
	    }
	}, timer); // Set the Timer time Delay
	while(!finished)
	{
	    try {
		Thread.sleep(200);
	    } catch (InterruptedException ex) {
		Logger.getLogger(EnterCubes.class.getName()).log(Level.SEVERE, null, ex);
	    }
	}
	finished = false;
	arrCubes[0] = cube1;
	arrCubes[1] = cube2;
	this.dispose();
	return arrCubes;
    }
}
